//
//  AlwaysTools.m
//  AppMacros
//
//  Created by 姚敦鹏 on 2017/9/12.
//  Copyright © 2017年 Encifang. All rights reserved.
//

#import "AlwaysTools.h"
#import <CommonCrypto/CommonDigest.h>

static AlwaysTools *_instance;


@implementation AlwaysTools

#pragma mark --
#pragma mark -- 正则判断
+(BOOL) validateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+(BOOL) validateMobile:(NSString *)phone {
    
    //手机号以13，15，17，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

+(BOOL)validateUserName:(NSString *)userName
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    return [userNamePredicate evaluateWithObject:userName];
}

+(BOOL)validateNickname:(NSString *)nickeName
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickeName];
}

+ (BOOL)validatePassword:(NSString *)passWord minLength:(NSString *)minNum maxLength:(NSString *)maxNum
{
    NSString *regex = [NSString stringWithFormat:@"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{%@,%@}$",minNum,maxNum];
    //6-20位数字和字母组成
    //    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [passWordPredicate evaluateWithObject:passWord];
}

+(BOOL) validateTelephone:(NSString *)phone {
    
    NSString * PHS = @"^([0-9]{3}-?[0-9]{8})|([0-9]{4}-?[0-9]{7,8})$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",PHS];
    return [phoneTest evaluateWithObject:phone];
}

+(BOOL)checkCardNo:(NSString*) cardNo {
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1]intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength -1];
    for (int i = cardNoLength -1; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1,1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else {
        return NO;
    }
}

+(BOOL)validateIdentityCard:(NSString *)cart {
    BOOL flag;
    if (cart.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:cart];
}

+ (BOOL)stringIsEmpty:(NSString *)string {
    
    if (string == nil ||
        [string isKindOfClass:[NSNull class]] ||
        string.length == 0 ||
        [string isEqualToString:@""] ||
        ![string isKindOfClass:[NSString class]])
        return YES;
    else return NO;
}

+(BOOL)validateUrl:(NSString *)urlStr
{
    NSString * regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:urlStr];
}

+(BOOL)validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:self];
}

+(BOOL)validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}


#pragma mark --
#pragma mark -- 加密
+(NSString *)base64:(NSString *)string
{
    // Create NSData object
    NSData *nsdata = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    // Get NSString from NSData object in Base64
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
    // Print the Base64 encoded string
    return base64Encoded;
}

+(NSString *)base64Decoded:(NSString *)string
{
    // NSData from the Base64 encoded str
    NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:string options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    
    return base64Decoded;
}

+(NSString *)MD5Hash:(NSString *)string  isLower:(BOOL)isLower
{
    const char *cStr = [string UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    NSString *md5 = [NSString stringWithFormat:
                     @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                     result[0], result[1], result[2], result[3],
                     result[4], result[5], result[6], result[7],
                     result[8], result[9], result[10], result[11],
                     result[12], result[13], result[14], result[15]];
    return isLower ? [md5 lowercaseString] : md5;
}



#pragma mark --
#pragma mark -- 计算文字的 宽、高、size
+(CGSize)ydp_boundingRectWithSize:(CGSize)size
                     withTextFont:(UIFont *)font
                          content:(NSString *)content
{
    if ([self stringIsEmpty:content]) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = 0;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    return [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}

+(CGFloat)ydp_heightWithFont:(UIFont *)font
          constrainedToWidth:(CGFloat)width
                     content:(NSString *)content
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    
    CGSize textSize;
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                         options:(NSStringDrawingUsesLineFragmentOrigin |
                                                  NSStringDrawingTruncatesLastVisibleLine)
                                      attributes:attributes
                                         context:nil].size;
    } else {
        textSize = [content sizeWithFont:textFont
                       constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)
                           lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                     options:(NSStringDrawingUsesLineFragmentOrigin |
                                              NSStringDrawingTruncatesLastVisibleLine)
                                  attributes:attributes
                                     context:nil].size;
#endif
    
    return ceil(textSize.height);
}

+(CGFloat)ydp_widthWithFont:(UIFont *)font
        constrainedToHeight:(CGFloat)height
                    content:(NSString *)content
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    
    CGSize textSize;
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [content boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                         options:(NSStringDrawingUsesLineFragmentOrigin |
                                                  NSStringDrawingTruncatesLastVisibleLine)
                                      attributes:attributes
                                         context:nil].size;
    } else {
        textSize = [content sizeWithFont:textFont
                       constrainedToSize:CGSizeMake(CGFLOAT_MAX, height)
                           lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [content boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                     options:(NSStringDrawingUsesLineFragmentOrigin |
                                              NSStringDrawingTruncatesLastVisibleLine)
                                  attributes:attributes
                                     context:nil].size;
#endif
    
    return ceil(textSize.width);
}

+(CGSize)ydp_sizeWithFont:(UIFont *)font
       constrainedToWidth:(CGFloat)width
                  content:(NSString *)content
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    
    CGSize textSize;
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                         options:(NSStringDrawingUsesLineFragmentOrigin |
                                                  NSStringDrawingTruncatesLastVisibleLine)
                                      attributes:attributes
                                         context:nil].size;
    } else {
        textSize = [content sizeWithFont:textFont
                       constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)
                           lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                     options:(NSStringDrawingUsesLineFragmentOrigin |
                                              NSStringDrawingTruncatesLastVisibleLine)
                                  attributes:attributes
                                     context:nil].size;
#endif
    
    return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}
/**
 *  @brief 计算文字的大小
 *
 *  @param font   字体(默认为系统字体)
 *  @param height 约束高度
 */
+(CGSize)ydp_sizeWithFont:(UIFont *)font
      constrainedToHeight:(CGFloat)height
                  content:(NSString *)content
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    
    CGSize textSize;
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [content boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                         options:(NSStringDrawingUsesLineFragmentOrigin |
                                                  NSStringDrawingTruncatesLastVisibleLine)
                                      attributes:attributes
                                         context:nil].size;
    } else {
        textSize = [content sizeWithFont:textFont
                       constrainedToSize:CGSizeMake(CGFLOAT_MAX, height)
                           lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [content boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                     options:(NSStringDrawingUsesLineFragmentOrigin |
                                              NSStringDrawingTruncatesLastVisibleLine)
                                  attributes:attributes
                                     context:nil].size;
#endif
    
    return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}


#pragma mark --
#pragma mark -- 沙河路径
+ (NSString *)getSandboxPath
{
    NSString *Path = @"~";
    Path = [Path stringByExpandingTildeInPath];
    
    return Path;
}

+ (BOOL)isExistWithPath:(NSString *)path
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return YES;
    }else{
        return NO;
    }
}

+ (NSString *)getPath:(NSString *)path name:(NSString *)name
{
    path = [path stringByExpandingTildeInPath];//扩展成路径
    NSString *FilePath = [path stringByAppendingPathComponent:name];
    return FilePath;
}

+ (void)saveFileWithPath:(NSString *)path FileName:(NSString *)name content:(id)content
{
    NSString *FilePath = nil;
    NSString *file = [path lastPathComponent];
    NSRange range = [file rangeOfString:@"."];
    if (range.location != NSNotFound) {
        FilePath = path;
    }else{
        path = [path stringByExpandingTildeInPath];//扩展成路径
        FilePath = [path stringByAppendingPathComponent:name];
    }
    
    NSError *error = nil;
    if (content==NULL) {
        [self PrintlnString:error.description headName:@"数据为空,写入失败"];
        return;
    }
    if ([content isKindOfClass:[NSString class]]) {
        NSString *data = content;
        [data writeToFile:FilePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
    if ([content isKindOfClass:[NSArray class]]) {
        NSArray *data = content;
        [data writeToFile:FilePath atomically:YES];
    }
    if ([content isKindOfClass:[NSDictionary class]]) {
        NSDictionary *data = content;
        [data writeToFile:FilePath atomically:YES];
    }
    if ([content isKindOfClass:[NSData class]]) {
        NSData *data = content;
        [data writeToFile:FilePath atomically:YES];
    }
    
    if (error) {
        [self PrintlnString:error.description headName:@"错误:"];
    }
}

+ (NSData *)readFileWithPath:(NSString *)path FileName:(NSString *)name
{
    if (!path || path.length <= 0) {
        return nil;
    }
    NSString *lastPart = [path lastPathComponent];
    if (![lastPart hasSuffix:@".xml"]) {
        path = [path stringByExpandingTildeInPath];//扩展成路径
        path = [path stringByAppendingPathComponent:name];
        if (![path hasSuffix:@".xml"]) {
            path = [path stringByAppendingString:@".xml"];
        }
    }
    NSString *FilePath = path;
    if (![self isExistWithPath:FilePath]) {
        return NULL;
    }
    NSData *data = [[NSData alloc] initWithContentsOfFile:FilePath];
    return data;
}

+ (id)readWithPath:(NSString *)path FileName:(NSString *)name
{
    NSError *error = nil;
    name = [name stringByAppendingString:@".xml"];
    NSData *data = [self readFileWithPath:path FileName:name];
    if (data==NULL) {
        return NULL;
    }
    id josonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        [self PrintlnString:error.localizedDescription headName:@"错误:"];
        return NULL;
    }
    return josonDic;
}

+ (void)PrintlnString:(id)obj headName:(NSString *)name
{
    if (!obj && !name) {
        return;
    }
    if (!obj) {
        NSLog(@"%@",name);
        return;
    }
    if (!name) {
        NSLog(@"%@",obj);
        return;
    }
    NSLog(@"%@%@",name,obj);
}


#pragma mark -- =============textField=========================
+(void)attributedString:(NSString *)attString andHolderColor:(UIColor *)color placeholder:(UITextField *)textField imageString:(NSString *)imageString andImageRect:(CGRect)imageRect {
    
    NSMutableAttributedString *att = [self attributedString:attString andColor:color];
    textField.attributedPlaceholder = att;
    UIImageView *searImage = [[UIImageView alloc] initWithFrame:imageRect];
    searImage.image = [UIImage imageNamed:imageString];
    textField.leftView = searImage;
    textField.leftViewMode = UITextFieldViewModeAlways;
}

//设置左边text间距
+(void)textFieldLeftMargin:(CGFloat)margin
               placeholder:(UITextField *)textField, ...NS_REQUIRES_NIL_TERMINATION
{
    va_list args;
    // scan for arguments after firstObject.
    va_start(args, textField);
    
    // get rest of the objects until nil is found
    for (UITextField *v = textField; v != nil; v = va_arg(args,UITextField *)) {
        v.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, margin, textField.frame.size.height)];
        v.leftViewMode = UITextFieldViewModeAlways;
    }
    
    va_end(args);
}

#pragma mark - =============颜色转图片=========================
+ (UIImage *)imgColor:(UIColor *)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark -- 
#pragma mark -- NSMutableAttributedString
+(NSMutableAttributedString *)attributedString:(NSString *)String andFontOfSize:(CGFloat)Size andRange:(NSRange)Range{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:String];
    [attributedString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Size]} range:Range];
    
    return attributedString;
}

+(NSMutableAttributedString *)attributedString:(NSString *)String andColor:(UIColor *)Color andRange:(NSRange)Range{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:String];
    [attributedString setAttributes:@{NSForegroundColorAttributeName:Color} range:Range];
    
    return attributedString;
}

+(NSMutableAttributedString *)attributedString:(NSString *)String andColor:(UIColor *)Color {
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:String attributes:@{NSForegroundColorAttributeName:Color}];
    
    return attributedString;
}

#pragma mark -- 
#pragma mark -- NSDate
+ (NSString *)getDateWithFormat:(NSString *)format
{
    return [self getSystemTime:[NSDate date] format:format];
}

+ (NSString *)getSystemTime:(NSDate *)date format:(NSString *)format
{
    if (date==NULL) {
        date = [NSDate date];
    }
    NSDateFormatter *data_time = [[NSDateFormatter alloc]init];
    [data_time setDateFormat:[self stringIsEmpty:format] ? @"yyyy-MM-dd HH:mm:ss" : format];
    return [data_time stringFromDate:date];
}

+(NSInteger)DateString:(NSString*)DateString DateFormat:(NSString*)Format
{
    //NSDateFormatter实例
    NSDateFormatter *form= [[NSDateFormatter alloc] init];
    //NSDateFormatter格式化
    [form setDateFormat:Format];
    NSDate * date = [form dateFromString:DateString];
    NSInteger count  = [date  timeIntervalSince1970];
    return count;
}

+(BOOL)ydp_isToday:(NSDate *)date {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components1 = [calendar components:(NSCalendarUnitYear
                                                          | NSCalendarUnitMonth
                                                          | NSCalendarUnitDay)
                                                fromDate:[NSDate date]];
    NSDateComponents *components2 = [calendar components:(NSCalendarUnitYear
                                                          | NSCalendarUnitMonth
                                                          | NSCalendarUnitDay)
                                                fromDate:date];
    return ([components1 year] == [components2 year]
            && [components1 month] == [components2 month]
            && [components1 day] == [components2 day]);
}

+(NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

+(NSDate *)dateWithTimeIntervalString:(NSString *)timeString
{
    return [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
}


#pragma mark -- NSError
+ (NSError *)initWithMsg:(NSString *)errMsg code:(NSInteger)code
{
    NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey];
				
    NSError *errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainPOSIX" code:code userInfo:info];
    
    return errPtr;
}

+(id)shareAlwaysTool {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

@end
